<template>
    <div>
        <div class="create-exam-top">
            <div :class="{ active: isActive == 1 }">
                <span class="top-num">1</span>
                <span class="word">第一步：选择试卷</span>
            </div>
            <div :class="{ active: isActive == 2 }">
                <span class="top-num">2</span>
                <span class="word">第二步：发布考试</span>
            </div>
        </div>
        <div>
            <examPaper v-if="!route.query.examPaperId && !route.query.examId" @emitNextStep="emitNextStep" />
            <div v-if="route.query.examPaperId || route.query.examId" class="create-exam-step2">
                <div class="step2-left">
                    <el-form :model="examForm" label-width="auto" style="max-width: 550px" class="exam-form">
                        <el-form-item label="考试名称">
                            <el-input v-model="examForm.examName" :placeholder="`${examPaperData.epName}`" />
                        </el-form-item>
                        <el-form-item label="考试学期" v-model="examForm.semester" class="semester">
                            <el-input class="semester-input" v-model="semesterYear" />年
                            <el-select v-model="semesterValue" class="semester-select" placeholder="">
                                <el-option value="上" label="上">上</el-option>
                                <el-option value="下" label="下">下</el-option>
                            </el-select>学期
                        </el-form-item>
                        <el-form-item label="发布时间">
                            <el-date-picker v-model="examForm.examPublishTime" type="datetime" placeholder="选择发布时间"
                                :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                        <el-form-item label="考试时间">
                            <el-date-picker v-model="examForm.examBeginTime" type="datetime" placeholder="选择开始时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                            <span class="time-middle">到</span>
                            <el-date-picker v-model="examForm.examEndTime" type="datetime" placeholder="选择结束时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                        <el-form-item label="答卷时长">
                            <el-input class="answering-time" :disabled="true"
                                :placeholder="getAnswerTime(examForm.examBeginTime, examForm.examEndTime)" />分钟
                        </el-form-item>
                        <el-form-item label="参与班级">
                            <!-- <el-cascader :options="deptOptions" v-model="examForm.classId" :props="props"
                                placeholder="选择班级" :show-all-levels="false" filterable class="dialog-select" /> -->
                            <el-select v-model="examForm.classId" multiple collapse-tags collapse-tags-tooltip
                                :max-collapse-tags="3" class="multiple-select" placeholder="选择班级">
                                <el-option v-for="item in deptOptions" :label="item.deptName" :value="item.id"
                                    class="multiple-option" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <div class="form-description">
                                <div class="description-head">
                                    考试说明
                                </div>
                                <el-input type="textarea" v-model="examForm.examDescription"></el-input>
                            </div>
                        </el-form-item>

                    </el-form>
                </div>
                <div class="step2-right">
                    <div class="right-h1">
                        <div class="right-head">
                            <div class="head-m1">
                                <div>{{ examPaperData.epName }}</div>
                                <div class="m1-right">
                                    <div class="m1-word" @click="watchExamDetail(route.query.examPaperId)">预览试卷</div>
                                    <span class="m1-padding">|</span>
                                    <div class="m1-word">编辑试卷</div>
                                </div>
                            </div>
                            <div class="body-m1">
                                <div class="right-body">
                                    <div class="right-body-word">总分:</div>
                                    <span>{{ examPaperData.epScore }}.0</span>
                                </div>
                                <div class="right-body">
                                    <div class="right-body-word">题目数量:</div>
                                    <span>{{ examPaperData.epQuestionNumber }}</span>
                                </div>
                                <div class="right-body">
                                    <div class="right-body-word">创建人:</div>
                                    <span>{{ examPaperData.creator }}</span>
                                </div>
                                <div class="right-body">
                                    <div class="right-body-word">创建日期:</div>
                                    <span>{{ examPaperData.createTime }}</span>
                                </div>

                            </div>
                        </div>
                    </div>
                    <div class="right-btn">
                        <el-button type="primary" @click="onPublicExam(examForm)" v-if="route.query.examPaperId"><i
                                class="iconfont icon-fabu"></i>发布考试</el-button>
                        <el-button type="primary" @click="onSaveExam(examForm)"
                            v-if="route.query.examId && !route.query.check"><i
                                class="iconfont icon-baocun"></i>保存</el-button>
                        <el-button type="primary" @click="toBack" v-if="route.query.check"><i
                                class="iconfont icon-fanhui"></i>返回</el-button>

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { createExamAPI, selectExamPaperAPI, getExamDetailAPI, updateExamAPI, findNodesAPI } from '@/api/api'
import examPaper from './examPaper.vue';
import { ElMessage } from 'element-plus';


const route = useRoute()
const router = useRouter()


const isActive = ref(1)
const stepOne = ref(true)

const semesterYear = ref('')
const semesterValue = ref('')
const value = ref('')
const deptOptions = ref([])
const props = { multiple: true }
const examPaperData = ref({
    epName: '',
    epScore: '',
    epQuestionNumber: '',
    creator: '',
    createTime: '',

})
const examForm = reactive({
    examName: '',
    semester: '',
    examPublishTime: '',
    examBeginTime: '',
    examEndTime: '',
    courseId: '',
    examDescription: '',
    classId: [],
    examPaperId: [],
})
const shortcuts = [
    {
        text: '今天',
        value: new Date(),
    },
    {
        text: '明天',
        value: () => {
            const date = new Date()
            date.setDate(date.getDate() - 1)
            return date
        },
    },
    {
        text: '一周后',
        value: () => {
            const date = new Date()
            date.setDate(date.getDate() - 7)
            return date
        },
    },
]
onMounted(() => {
    findNodes()
    if (route.query.examPaperId) {
        isActive.value = 2
        getExamPaperDetail(route.query.examPaperId)
    }
    if (route.query.examId) {
        isActive.value = 2
        getExamDetail(route.query.examId)
    }
})
//获取所有部门信息
const findNodes = async () => {
    await findNodesAPI().then(res => {
        if (res.data.code == 200) {
            getTreeData(res.data.data)
        }
    })
}
//获取树形部门
const getTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
        data[i].label = data[i].deptName
        data[i].value = data[i].id
        if (data[i].children == null || data[i].children.length < 1) {
            data[i].children = undefined     //避免children为空的时候，下一级显示为空白
            if (data[i].deptLevel == 3) {
                deptOptions.value.push(data[i]) 
            }
        }
        else {
            getTreeData(data[i].children)
        }
    }
}
//子组件触发，下一步
const emitNextStep = () => {
    isActive.value = 2
    stepOne.value = false
}
//返回上一页面
const toBack = () => {
    router.back();
}
//计算考试时长
const getAnswerTime = (start, end) => {
    let staytimeGap = new Date(end).getTime() - new Date(start).getTime();
    let minutes = parseInt(staytimeGap / 60000) // 得到分钟数
    if (!minutes) {
        return '0'
    }
    minutes = String(minutes)
    return minutes
}
//获取试卷信息
const getExamPaperDetail = async (epId) => {
    await selectExamPaperAPI(epId).then(res => {
        examPaperData.value = res.data.data
        examForm.examPaperId.push(Number(epId))
        if (!route.query.examId) {
            examForm.examName = examPaperData.value.epName
        }
    })
}
//教师获取考试详情
const getExamDetail = async (examId) => {
    await getExamDetailAPI(examId).then(res => {
        examForm.examName = res.data.data.examName
        examForm.examPublishTime = res.data.data.examPublishTime
        examForm.examBeginTime = res.data.data.examBeginTime
        examForm.examEndTime = res.data.data.examEndTime
        examForm.examDescription = res.data.data.examDescription
        examForm.examId = res.data.data.examId
        semesterYear.value = res.data.data.semester.slice(0, 4)
        semesterValue.value = res.data.data.semester.slice(5, 6)
        getExamPaperDetail(Number(res.data.data.examPaperId))
    })
}
//预览试卷
const watchExamDetail = (epId) => {
    router.push({
        name: 'examPaperDetail',
        query: {
            epId: epId
        }
    })
}
//发布考试
const onPublicExam = async (examForm) => {
    examForm.semester = semesterYear.value + '年' + semesterValue.value + '学期'
    examForm.courseId = Number(sessionStorage.getItem('examPaperCourseId'))
    for (let i = 0; i < deptOptions.value.length; i++) {
        const element = deptOptions.value[i];
        examForm.classId.push(element.id)
    }
    await createExamAPI(examForm).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('创建考试成功')
            router.push({
                path: '/adminHome/manageExam'
            })
        } else {
            ElMessage.warning(res.data.message)
        }
    })
}
//更新考试信息
const onSaveExam = async (examForm) => {
    // examForm.semester = semesterYear.value + '年' + semesterValue.value + '学期'
    delete examForm['semester']
    examForm.courseId = Number(sessionStorage.getItem('examPaperCourseId'))
    await updateExamAPI(examForm).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('更新考试成功')
        } else {
            ElMessage.warning(res.data.message)
        }
    })
}

</script>

<style lang="less">
// 添加颜色类
.el-radio__input.is-checked+.el-radio__label {
    color: grey !important;
}
</style>

<style lang="less" scoped>
.create-exam-top {
    min-height: 50px;
    background-color: #fff;
    width: 100%;
    margin-top: 5px;
    border-bottom: 1px solid #409eff;
    display: flex;
    justify-content: space-around;
    line-height: 50px;

    .word {
        color: #bfbfbf;
    }

    .top-num {
        font-size: 16px;
        font-weight: 550;
        margin-right: 10px;
        border: 1px solid #bfbfbf;
        padding: 2px 8px;
        border-radius: 20px;
        color: #bfbfbf;
    }

    .active .top-num {
        color: #fff;
        background-color: #409eff;
        border: 1px solid #409eff;
    }

    .active .word {
        color: black;
    }
}

.create-exam-step2 {
    background-color: #fff;
    min-height: 80vh;
    margin: 10px 0;
    overflow: scroll;
    display: flex;

    .step2-left {
        min-height: 74vh;
        min-width: 40.7vw;
        padding: 10px 20px;
        margin-top: 20px;

        .exam-form {
            margin-left: 25px;

            .semester {
                display: flex;

                .semester-input {
                    width: 60px;
                    margin: 0 5px;
                }

                .semester-select {
                    width: 60px;
                    margin: 0 5px;

                }
            }

            .time-middle {
                margin: 0 8px;
            }

            .answering-time {
                width: 60px;
                margin-right: 8px;
            }

            .form-description {
                width: 35vw;
                margin: 10px 0 20px 0;

                .description-head {
                    border: 1px solid rgb(207, 206, 206);
                    border-bottom: none;
                    height: 30px;
                    line-height: 30px;
                    background-color: #edf0f6;
                    padding: 10px 20px;
                }

            }
        }

    }

    .step2-right {
        min-height: 74vh;
        min-width: 38.5vw;
        padding: 10px;

        .right-h1 {
            border: 1px solid rgb(207, 206, 206);
            min-height: 200px;
            margin: 10px 0 20px 0;

            .right-head {
                height: 30px;
                line-height: 30px;
                background-color: #edf0f6;
                padding: 10px 20px;


                .head-m1 {
                    display: flex;
                    justify-content: space-between;

                    .m1-right {
                        display: flex;

                        .m1-word {
                            color: #409eff;
                        }

                        .m1-padding {
                            margin: 0 10px;
                            color: #bfbfbf;
                        }
                    }

                }

                .body-m1 {
                    padding: 20px 10px;

                    .right-body {
                        display: flex;

                        .right-body-word {
                            color: grey;
                            margin-right: 10px;
                            font-size: 14px;
                        }
                    }


                }
            }
        }

        .right-btn {
            position: absolute;
            right: 80px;

            .el-button {
                width: 120px;

                .iconfont {
                    margin: 0 5px;
                    font-size: 14px;
                }
            }

        }




    }
}

/deep/ .el-radio__input.is-checked .el-radio__inner::after {
    content: '';
    width: 8px;
    height: 3px;
    border: 2px solid white;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 2px;
    left: 1px;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
}
</style>